package com.xph.core.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class XSSFilter implements Filter {
	
	private static Logger log = Logger.getLogger(XSSFilter.class);

	private static final String SEPERATOR = ";";
	public static final String FILTERSCRIPTS = "filterScripts";
	private static String[] scripts;

	/**
	 * 是否是一个SQL注入 即同时包含有 （and|or|having） 和 = 号
	 * 
	 * @param input
	 *            String
	 * @return boolean
	 */
	public static boolean isSQLInject(String input) {
		boolean result = true;
		Matcher m = Pattern.compile(".+(([aA][nN][dD])|([oO][rR])|([hH][aA][vV][iI][nN][gG])).+=.+").matcher(input);
		result = m.matches();
		return result;
	}
	
	public void init(FilterConfig filterConfig) throws ServletException {
		String str = filterConfig.getInitParameter(FILTERSCRIPTS);
		scripts = str.split( SEPERATOR );
	}
	
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) servletRequest;
		boolean isSafe = true;
		String queryString = req.getQueryString();
//        queryString=queryString+URLDecoder.decode(queryString);
		log.debug("获取当前参数："+queryString);
		//当url请求是第三方开放rest接口添加新章节时，不做XSS检查
		if(req.getRequestURI().toString().contains("addNewChapter"))
		{
		    filterChain.doFilter(servletRequest, servletResponse);
		    return;
		}
		
		if (null!=queryString  && queryString.length() > 0) {
			for (int i = 0; i < scripts.length; i++) {
				if (queryString.toLowerCase().indexOf(scripts[i]) >= 0) {
					log.error("GET request parameters[" + queryString + "] has illegal request script[" + scripts[i] + "] which is dangerous to the system.");
					isSafe = false;
					break;
				}
			}
		}

		if (isSafe) {
			Map paras = req.getParameterMap();
			Iterator keyIt = paras.keySet().iterator();

				while (keyIt.hasNext() && isSafe) {
					String key = keyIt.next().toString();
					// XSS检测
					for (int i = 0; i < scripts.length; i++) {
						if (req.getParameter(key).toLowerCase().indexOf(scripts[i]) >= 0 || key.toLowerCase().indexOf(scripts[i]) >= 0 || req.getParameter(key).toLowerCase().indexOf("</script>") >= 0) {
							log.error("POST request parameters["+key+":"+req.getParameter(key)+"] has illegal request script[" + scripts[i] + "] which is dangerous to the system.");
							isSafe = false;
							break;
						}else if("'".equals(req.getParameter(key))||";".equals(req.getParameter(key))){
							log.error("POST request parameters["+key+":"+req.getParameter(key)+"] has illegal request script[' or ;] which is dangerous to the system.");
							isSafe = false;
							break;
						}
					}
				}
			

		}

		if (!isSafe) {
			log.error("Illegal URL, Access Forbidden!");
			HttpServletResponse response = (HttpServletResponse)servletResponse;
			response.setContentType ("text/html;charset=GBK");
			//response.sendError( 404 );			
			PrintWriter pw = servletResponse.getWriter();
			pw.write("禁止访问：含有非法的请求参数");
			pw.close();
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}

	}

	public void destroy() {
	}
}
